package com.allm.ai.common.service;

import com.allm.ai.common.entity.ModelTag;
import com.allm.ai.common.repository.ModelTagRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 模型标签服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ModelTagService {

    private final ModelTagRepository modelTagRepository;

    /**
     * 获取所有启用的标签
     */
    public List<ModelTag> getAllActiveTags() {
        return modelTagRepository.findByIsActiveTrueOrderBySortOrder();
    }

    /**
     * 根据ID获取标签
     */
    public Optional<ModelTag> getTagById(Long id) {
        return modelTagRepository.findById(id);
    }

    /**
     * 根据名称获取标签
     */
    public Optional<ModelTag> getTagByName(String name) {
        return modelTagRepository.findByName(name);
    }

    /**
     * 创建标签
     */
    @Transactional
    public ModelTag createTag(ModelTag tag) {
        if (modelTagRepository.existsByName(tag.getName())) {
            throw new IllegalArgumentException("标签名称已存在: " + tag.getName());
        }
        return modelTagRepository.save(tag);
    }

    /**
     * 更新标签
     */
    @Transactional
    public ModelTag updateTag(Long id, ModelTag tag) {
        ModelTag existingTag = modelTagRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("标签不存在: " + id));
        
        if (!existingTag.getName().equals(tag.getName()) && 
            modelTagRepository.existsByName(tag.getName())) {
            throw new IllegalArgumentException("标签名称已存在: " + tag.getName());
        }
        
        existingTag.setName(tag.getName());
        existingTag.setColor(tag.getColor());
        existingTag.setIconClass(tag.getIconClass());
        existingTag.setDescription(tag.getDescription());
        existingTag.setIsActive(tag.getIsActive());
        existingTag.setSortOrder(tag.getSortOrder());
        
        return modelTagRepository.save(existingTag);
    }

    /**
     * 删除标签
     */
    @Transactional
    public void deleteTag(Long id) {
        if (!modelTagRepository.existsById(id)) {
            throw new IllegalArgumentException("标签不存在: " + id);
        }
        modelTagRepository.deleteById(id);
    }
}
